package com.hm.health.widget;

import android.app.AlertDialog;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.TextView;

import com.goodix.entity.HCIFilterParam;
import com.goodix.libromablecom.sdk.cardiff.arguments.StartArgumentsKeyEnum;
import com.goodix.utils.DefaultSpUtil;
import com.goodix.utils.ToastUtils;
import com.hm.health.MyApplication;
import com.hm.health.R;
import com.hm.health.Utils.HciFileHeartRateFetcher;
import com.hm.health.entity.arguments.StartArgumentsManager;
import com.hm.health.provider.DbProvider;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * @author chenshi
 */
public class InputTestConditionDialog extends AlertDialog {
    private static final String TAG = "InputSceneDialog";

    private static final String KEY_LAST_SCENE = "key_last_scene";
    public static final String KEY_SPO2_COMPARE_DEVICE_NAME = "key_spo2_compare_device_name";
    public static final String PREFS_KEY_SUBJECT_NAME = "prefs_key_subject_name";

    @BindView(R.id.scene_name_spinner)
    Spinner mSceneNameSpinner;
    @BindView(R.id.scene_name_fram)
    TableRow mSceneNameFram;
    @BindView(R.id.earhang_spinner)
    Spinner mEarHangSpinner;
    @BindView(R.id.earhang_name)
    TableRow mTrEarHangName;
    @BindView(R.id.sp_alg_value_strategy)
    Spinner mSpAlgValueStrategy;
    @BindView(R.id.tr_alg_strategy)
    TableRow mTrAlgStrategy;
    @BindView(R.id.sp_hci_device)
    Spinner mHciDeviceSpinner;
    @BindView(R.id.ll_hci_device)
    TableRow mLlHciDevice;
    @BindView(R.id.subject_name_spinner)
    EditText mSubjectNameEdit;
    @BindView(R.id.subject_name_fram)
    TableRow mSubjectNameFram;
    @BindView(R.id.sp_measurement_mode)
    Spinner mSpMeasurementMode;

    @BindView(R.id.et_spo2_compare_device_name)
    EditText mEtSpo2CompareDeviceName;

    @BindView(R.id.tv_manual_input_device_name)
    TextView mTvManualInputDeviceName;

    private Context mContext;
    private ClickListenerInterface mClickListenerInterface;

    /** Scene information */
    private List<String> mSceneDataArray = new ArrayList<String>();
    private List<Integer> mSceneIDArray = new ArrayList<Integer>();

    /** Ear Hang information */
    private List<String> mEarHangDataArray = new ArrayList<String>();
    private List<Integer> mEarHangIDArray = new ArrayList<Integer>();

    /** HCI device information */
    private boolean mIsSelectHciDevice = true;
    private List<String> mHcideviceArray = new ArrayList<String>();

    private boolean mIsEditable = true;

    /**
     * The interface Click listener interface.
     */
    public interface ClickListenerInterface {
        /**
         * Do confirm.
         *
         * @param subjectName          the subject name
         * @param sceneID              the scene id
         * @param sceneNam             the scene nam
         * @param earHangID            the ear hang id
         * @param earHang              the ear hang
         * @param algCalculateStrategy the alg calculate strategy
         */
        void doConfirm(String subjectName,
                       int sceneID, String sceneNam,
                       int earHangID, String earHang,
                       int algCalculateStrategy,
                       int measurementMode);

        /**
         * Do cancel.
         */
        void doCancel();
    }

    /**
     * Instantiates a new Input scene query params dialog ex.
     *
     * @param context the context
     */
    public InputTestConditionDialog(Context context) {
        this(context, true);
    }

    public InputTestConditionDialog(Context context, boolean editable) {
        super(context, R.style.MyDialog);
        mContext = context;
        mIsEditable = editable;
    }

    /**
     * Sets is select hci device.
     *
     * @param isSelectHciDevice the is select hci device
     */
    public void setIsSelectHciDevice(boolean isSelectHciDevice) {
        mIsSelectHciDevice = isSelectHciDevice;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View view = inflater.inflate(R.layout.layout_input_scene_params_dialog_ex, null);
        setContentView(view);
        ButterKnife.bind(this, view);
        sortScenes();
        initView(view);
        initDisplayStyle();
        fillSceneDataFromDatabase();
        fillEarDataFromDB();
    }


    private String[] sortScenes(){
        String[] scenes = mContext.getResources().getStringArray(R.array.test_scene_array);
        String lastScene = DefaultSpUtil.getValue(mContext, KEY_LAST_SCENE, "");
        mSceneDataArray = sortScenes(scenes, lastScene);
        Spinner spinner = findViewById(R.id.scene_name_spinner);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_item, mSceneDataArray);
        spinner.setAdapter(adapter);
        return scenes;
    }

    private List<String> sortScenes(String[] scenes, String lastScene){
        List<String> sceneDataList = new ArrayList<>();
        if(null == scenes || scenes.length == 0){
            return sceneDataList;
        }
        if(null != lastScene && !lastScene.isEmpty()){
            sceneDataList.add(lastScene);
        }
        for(int index = 0; index < scenes.length; index++){
            if(null == lastScene || (!scenes[index].equals(lastScene))){
                sceneDataList.add(scenes[index]);
            }
        }
        return sceneDataList;
    }

    private void initHciDeviceSpinner(View rootView) {
        if (!mIsSelectHciDevice) {
            mLlHciDevice.setVisibility(View.GONE);
            return;
        }

        String currentHciDevice = HciFileHeartRateFetcher.getHciDevice(getContext());
        mHcideviceArray.add(currentHciDevice);

        List<HCIFilterParam> hciFilterParams = MyApplication.getHbdOptionIni().getHciFilter();
        insertDevice(HciFileHeartRateFetcher.DEVICE_NO, currentHciDevice);
        if (null != hciFilterParams && hciFilterParams.size() > 0) {
            for (HCIFilterParam p : hciFilterParams) {
                insertDevice(p.getDeviceName(), currentHciDevice);
            }
        }

        ArrayAdapter<String> hciDeviceAdapter = new ArrayAdapter<String>(mContext,
                android.R.layout.simple_spinner_item, mHcideviceArray);
        hciDeviceAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mHciDeviceSpinner.setAdapter(hciDeviceAdapter);
        mHciDeviceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
                Log.i(TAG, "scene onItemSelected");
                String selectedHciDevice = adapterView.getItemAtPosition(position).toString();
                HciFileHeartRateFetcher.putHciDevice(getContext(), selectedHciDevice);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                Log.i(TAG, "hci device onNothingSelected");
            }
        });
    }

    private void insertDevice(String hciDevice, String currentHciDevice) {
        if (!hciDevice.equals(currentHciDevice)) {
            mHcideviceArray.add(hciDevice);
        }
    }

    /**
     * Init view.
     *
     * @param view the view
     */
    public void initView(View view) {
        mTrEarHangName.setVisibility(View.GONE);
        initManallyInputDeviceView(view);
        initHciDeviceSpinner(view);
        String name = DefaultSpUtil.getValue(mContext, PREFS_KEY_SUBJECT_NAME, "default");
        mSubjectNameEdit.setText(name);

        // ECG 测量时显示 单次测量和连续测量
        if (StartArgumentsManager.getInstance().getFunctionName().equals(StartArgumentsKeyEnum.AppFunction_ECG)) {
            findViewById(R.id.tr_measure_mode).setVisibility(View.GONE);
        } else {
            findViewById(R.id.tr_measure_mode).setVisibility(View.GONE);
        }

        mTrEarHangName.setVisibility(View.GONE);
        setTestInfoEditable(mIsEditable);
    }

    /**
     * loadConfig display style
     */
    protected void initDisplayStyle() {
        WindowManager windowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
        Rect rect = new Rect();
        display.getRectSize(rect);
        layoutParams.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;
        layoutParams.width = (int) (rect.width() * 0.85f);
    }

    private void initManallyInputDeviceView(View rootView) {
        String functionName = StartArgumentsManager.getInstance().getFunctionName();
        mTvManualInputDeviceName.setVisibility(View.GONE);
        mEtSpo2CompareDeviceName.setVisibility(View.GONE);
    }

    /**
     * On scene query confirm clicked.
     */
    @OnClick(R.id.scene_query_confirm)
    public void onSceneQueryConfirmClicked() {
        String selectedSubjectName = mSubjectNameEdit.getText().toString();
        DefaultSpUtil.put(mContext, PREFS_KEY_SUBJECT_NAME, selectedSubjectName);
        String spo2CompareDeviceName = mEtSpo2CompareDeviceName.getText().toString();
        if (selectedSubjectName.isEmpty()) {
            ToastUtils.showLongToastMessage(mContext, mContext.getString(R.string.please_input_tester_name));
        } else {
            if (selectedSubjectName.contains("_") || selectedSubjectName.contains("-")) {
                ToastUtils.showLongToastMessage(mContext, mContext.getString(R.string.error_char_tester_name));
                return;
            }

            int scenePosition = mSceneNameSpinner.getSelectedItemPosition();
//            int sceneId = mSceneIDArray.get(scenePosition);
            String sceneName = mSceneDataArray.get(scenePosition);

            int earHangPosition = mEarHangSpinner.getSelectedItemPosition();
            int earHangId = mEarHangIDArray.get(earHangPosition);
            String earHangName = mEarHangDataArray.get(earHangPosition);

            int algStrategyPos = mSpAlgValueStrategy.getSelectedItemPosition();
            DefaultSpUtil.put(mContext, KEY_LAST_SCENE, sceneName);
            saveDeviceName(mContext, spo2CompareDeviceName.replaceAll(" ", ""));

            int measureMentMode = mSpMeasurementMode.getSelectedItemPosition();
            mClickListenerInterface.doConfirm(selectedSubjectName,
                    0, sceneName, earHangId, earHangName, algStrategyPos,measureMentMode);
        }
    }

    /**
     * On scene query cancel clicked.
     */
    @OnClick(R.id.scene_query_cancel)
    public void onSceneQueryCancelClicked() {
        mClickListenerInterface.doCancel();
    }

    /**
     * Sets clicklistener.
     *
     * @param clickListenerInterface the click listener interface
     */
    public void setClicklistener(ClickListenerInterface clickListenerInterface) {
        mClickListenerInterface = clickListenerInterface;
    }

    private void fillSceneDataFromDatabase() {
        Log.i(TAG, "fillSceneDataFromDatabase");
        DbProvider.getInstance(mContext).open();

        //fill scene data
        Cursor sceneCursor = DbProvider.getInstance(mContext).getAllSceneInfo();
        int sceneIdColumnIndex = sceneCursor.getColumnIndex(DbProvider.SCENEINFO_SCENE_ID_COLUMN);
        int sceneNameColumnIndex = sceneCursor.getColumnIndex(DbProvider.SCENEINFO_SCENE_NAME_COLUMN);
        while (sceneCursor.moveToNext()) {
            mSceneIDArray.add(sceneCursor.getInt(sceneIdColumnIndex));
        }
        sceneCursor.close();

        DbProvider.getInstance(mContext).close();
        initSceneSpinner();
    }

    private void fillEarDataFromDB() {
        Log.i(TAG, "fillSceneDataFromDatabase");
        DbProvider.getInstance(mContext).open();

        //fill earhang data
        Cursor earHangCursor = DbProvider.getInstance(mContext).getAllEarHangInfo();
        int earHangIdColumnIndex = earHangCursor.getColumnIndex(DbProvider.EARHANGINFO_SCENE_ID_COLUMN);
        int earHangNameColumnIndex = earHangCursor.getColumnIndex(DbProvider.EARHANGINFO_SCENE_NAME_COLUMN);
        while (earHangCursor.moveToNext()) {
            mEarHangIDArray.add(earHangCursor.getInt(earHangIdColumnIndex));
            mEarHangDataArray.add(earHangCursor.getString(earHangNameColumnIndex));
        }
        earHangCursor.close();
        DbProvider.getInstance(mContext).close();
        initEarHangSpinner();
    }

    private void initSceneSpinner() {

        if ((null != mSceneIDArray) && mSceneIDArray.isEmpty()) {
            for (int i = 0; i < mSceneDataArray.size(); ++i) {
                mSceneIDArray.add(i);
            }
        }

        ArrayAdapter<String> sceneSpinnerAdapter = new ArrayAdapter<String>(mContext,
                android.R.layout.simple_spinner_item, mSceneDataArray);
        sceneSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mSceneNameSpinner.setAdapter(sceneSpinnerAdapter);
    }

    private void initEarHangSpinner() {
        if ((null != mEarHangDataArray) && mEarHangDataArray.isEmpty()) {
            mEarHangDataArray.add(mContext.getString(R.string.no_ear_brace_info));
            mEarHangDataArray.add(mContext.getString(R.string.small_ear_brace_0_dot_5mm));
            mEarHangDataArray.add(mContext.getString(R.string.small_ear_brace_0_dot_5mm));
            mEarHangDataArray.add(mContext.getString(R.string.big_ear_brace_0_dot_8mm));
            mEarHangDataArray.add(mContext.getString(R.string.middle_ear_brace_1_dot_0mm));
            mEarHangDataArray.add(mContext.getString(R.string.big_ear_brace_1_dot_2mm));
            mEarHangDataArray.add(mContext.getString(R.string.small_ear_brace_1_dot_0mm_with_radian_weaken));
            mEarHangDataArray.add(mContext.getString(R.string.middle_ear_brace_1_dot_0mm_with_radian_weaken));
            mEarHangDataArray.add(mContext.getString(R.string.big_ear_brace_1_dot_2mm_with_radian_weaken));
        }

        if ((null != mEarHangIDArray) && mEarHangIDArray.isEmpty()) {
            for (int i = 0; i < mEarHangDataArray.size(); ++i) {
                mEarHangIDArray.add(i);
            }
        }

        ArrayAdapter<String> earHangAdapter = new ArrayAdapter<String>(mContext,
                android.R.layout.simple_spinner_item, mEarHangDataArray);
        earHangAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mEarHangSpinner.setAdapter(earHangAdapter);
    }

    public static String getDeviceName(Context context) {
        String functionName = StartArgumentsManager.getInstance().getFunctionName();
        String key = String.format("%s_%s", KEY_SPO2_COMPARE_DEVICE_NAME, functionName);
        String deviceName = DefaultSpUtil.getValue(context, key, "");
        return deviceName;
    }

    public static void saveDeviceName(Context context, String deviceName) {
        String functionName = StartArgumentsManager.getInstance().getFunctionName();
        String key = String.format("%s_%s", KEY_SPO2_COMPARE_DEVICE_NAME, functionName);
        DefaultSpUtil.put(context, key, deviceName);
    }

    private void setTestInfoEditable(boolean editable) {
        mSceneNameSpinner.setEnabled(editable);
        mSpAlgValueStrategy.setEnabled(editable);
        mHciDeviceSpinner.setEnabled(editable);
        mSubjectNameEdit.setEnabled(editable);
    }
}
